import { Vec3 } from 'cc'

export class GridRandomPositions {
	RandomPositionGenerator(diceCount: number) {
		throw new Error('Method not implemented.')
	}
	private rows: number
	private cols: number
	private grid: boolean[][] = []

	constructor(
		private areaWidth: number, // 区域宽
		private areaHeight: number, // 区域高
		private cellWidth: number, // cell 宽
		private cellHeight: number, // cell 高
		private jitterFactor: number = 0.05, // 随机跳动参数
		private maxRotation: number = 15
	) {
		this.initGrid()
	}

	private initGrid() {
		this.rows = Math.floor(this.areaHeight / this.cellHeight)
		this.cols = Math.floor(this.areaWidth / this.cellWidth)
		console.log('initGrid', this.rows, this.cols)
		this.grid = Array(this.rows)
			.fill(false)
			.map(() => Array(this.cols).fill(false))
	}

	public getRandomPositions(count: number): Vec3[] {
		const positions: Vec3[] = []
		let emptyCells = this.getAllEmptyCells()

		while (emptyCells.length < count) {
			// 交替扩展行和列
			if (this.rows <= this.cols) {
				this.rows++
				this.grid.push(Array(this.cols).fill(false))
			} else {
				this.cols++
				this.grid.forEach(row => row.push(false))
			}
			emptyCells = this.getAllEmptyCells()
		}

		this.shuffleArray(emptyCells)
		for (let i = 0; i < count; i++) {
			const cell = emptyCells[i]
			positions.push(this.calculatePosition(cell.row, cell.col))
		}

		return positions
	}

	private calculatePosition(row: number, col: number): Vec3 {
		const baseX = (col + 0.5) * this.cellWidth - this.areaWidth / 2
		const baseY = (row + 0.5) * this.cellHeight - this.areaHeight / 2

		const offsetX = (Math.random() * 2 - 1) * this.cellWidth * this.jitterFactor
		const offsetY = (Math.random() * 2 - 1) * this.cellHeight * this.jitterFactor

		const rotation = (Math.random() * 2 - 1) * this.maxRotation

		return new Vec3(baseX + offsetX, baseY + offsetY, rotation)
	}

	private getAllEmptyCells(): { row: number; col: number }[] {
		const emptyCells = []
		for (let row = 0; row < this.rows; row++) {
			for (let col = 0; col < this.cols; col++) {
				// 禁止使用四个角落的单元格
				const isCorner =
					(row === 0 && col === 0) || // 第一行第一列
					(row === 0 && col === this.cols - 1) || // 第一行最后一列
					(row === this.rows - 1 && col === 0) || // 第一列最后一行
					(row === this.rows - 1 && col === this.cols - 1) // 最后一行最后一列

				if (!this.grid[row][col] && !isCorner) {
					emptyCells.push({ row, col })
				}
			}
		}
		return emptyCells
	}

	private shuffleArray(array: any[]) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1))
			;[array[i], array[j]] = [array[j], array[i]]
		}
	}

	public reset() {
		this.initGrid()
	}
}
